import 'package:flutter/material.dart';
import 'package:ddwidget/dd_widget_common.dart';

/// 简单toast方案
/// 提供默认文本toast + [时长] + [是否阻塞用户交互]
/// 提供自定义[child]，用于展现自定义toast。（如果存在child会忽略msg）
class DDToast {
  static BuildContext? _rootContext;
  static updateRootContext(BuildContext context) {
    _rootContext = context;
  }

  static OverlayEntry? _currentOvlayEntry;
  static show({
    required String msg,
    int millisecond = 2000,
    bool block = false,
    Widget? child,
  }) {
    assert(_rootContext != null, "请设置rootContext");
    final state = Overlay.of(_rootContext!);
    if (_currentOvlayEntry != null) {
      _currentOvlayEntry!.remove();
    }
    _currentOvlayEntry = OverlayEntry(
      builder: (context) {
        return DDToastWidget(
          block: block,
          msg: msg,
          millisecond: millisecond,
          child: child,
          complete: hide,
        );
      },
    );
    state?.insert(_currentOvlayEntry!);
  }

  static hide() {
    if (_currentOvlayEntry == null) {
      return;
    }
    _currentOvlayEntry!.remove();
  }
}

class DDToastWidget extends StatefulWidget {
  final String msg;
  final int millisecond;
  final bool block;
  final Widget? child;
  final Function()? complete;
  const DDToastWidget({
    Key? key,
    required this.msg,
    this.millisecond = 2000,
    this.block = false,
    this.child,
    this.complete,
  }) : super(key: key);

  @override
  _DDToastWidgetState createState() => _DDToastWidgetState();
}

class _DDToastWidgetState extends State<DDToastWidget> with TickerProviderStateMixin {
  AnimationController? _animationController;
  Animation<double>? _ani;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
    _ani = CurvedAnimation(
      parent: _animationController!,
      curve: Curves.easeOut,
    )..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          Future.delayed(
            Duration(milliseconds: widget.millisecond),
          ).then((value) {
            _animationController!.reverse();
          });
        } else if (status == AnimationStatus.dismissed) {
          if (widget.complete != null) {
            widget.complete!();
          }
        }
      });
    _animationController!.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.block ? const Color(0x00000000) : null,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AnimatedBuilder(
            animation: _ani!,
            builder: (BuildContext context, Widget? child) {
              return Opacity(
                opacity: _ani!.value,
                child: widget.child ??
                    Container(
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(4),
                        ),
                        color: Colors.black54,
                      ),
                      padding: const EdgeInsets.only(top: 4, bottom: 4, left: 8, right: 8),
                      margin: const EdgeInsets.all(20),
                      child: Text(
                        widget.msg,
                        style: TextStyle(
                          color: Colors.white.withAlpha((_ani!.value * 255.0).toInt()),
                          fontSize: 14,
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
              );
            },
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    ddlog("toast释放");
    _animationController!.dispose();
    super.dispose();
  }
}
